package springmvc.web.ingredients;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lombok.Data;

import org.dhbw.cocktail.Ingredient;
import org.dhbw.cocktail.mixer.ICocktailMixer;
import org.dhbw.cocktail.mixer.MixerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

/**
 * Controller that handles the creation of new ingredients
 * 
 * @author Roland von Werden
 */
@Data
public class CreateIngredientController implements Controller {


	@Autowired
	@Qualifier("cocktail_mixer_factory")
	MixerFactory mixerFactory;

	@Override
	public ModelAndView handleRequest(HttpServletRequest arg0,
			HttpServletResponse arg1) throws Exception {
		ModelAndView mav = new ModelAndView();
		// Create a new Ingredient
		try {
			if (arg0.getParameter("name") != null
					&& arg0.getParameter("amount") != null
					&& arg0.getParameter("unit") != null) {
				// Values of the new Ingredient
				String name = (String) arg0.getParameter("name");
				// unit of the new ingredient
				String unit = (String) arg0.getParameter("unit");
				// initial amount the ingredient will have
				double initialAmount = Double.valueOf(arg0
						.getParameter("amount"));
				// Save new ingredient
				Ingredient newIngredient = createIngredient(name,
						initialAmount, unit);
				mav.addObject("new_ingredient", newIngredient);
			}
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}
		return mav;
	}

	/**
	 * Create new Ingredient & persist it
	 * 
	 * @param name
	 *            Name of the ingredient
	 * @param initialAmount
	 *            amount that is available from the start
	 * @param unit
	 *            unit of the amount
	 * @return Returns the created ingredient
	 */
	private Ingredient createIngredient(String name, double initialAmount,
			String unit) {
		ICocktailMixer mixer = mixerFactory.getCocktailMixer();
		Ingredient ingr = new Ingredient(name, initialAmount, unit);
		mixer.saveIngredient(ingr);
		return ingr;
	}

}
